using System.Collections.Generic;
using System.IO.IsolatedStorage;
using System.Net.Browser;
using System.Runtime.InteropServices.Automation;
using System.Threading;
using System.Windows.Threading;
using Lib.Helper;
using MSIACCSL2.ApplicationStateServices;
using MSIACCSL2.AppParamServices;
using MSIACCSL2.CustomerServices;
using MSIACCSL2.ItemServices;
using MSIACCSL2.RoleServices;
using MSIACCSL2.SatuanServices;
using MSIACCSL2.UserServices;
using MSIACCSL2.ViewModels;
using MSIACCSL2.Views.Login;
using MSIACCSL2.WarehouseServices;
using System.Linq;

namespace MSIACCSL2
{
    using System;
    using System.Runtime.Serialization;
    using System.ServiceModel.DomainServices.Client.ApplicationServices;
    using System.Windows;
    using System.Windows.Controls;
    

    /// <summary>
    /// Main <see cref="Application"/> class.
    /// </summary>
    public partial class App : Application
    {
        private BusyIndicator busyIndicator;
        private ApplicationStateServices.AplicationStateServicesClient AppClient;
        private IsolatedStorageSettings UserSettings;
        private IsolatedStorageFile file;
        private WarehouseServices.WarehouseServicesClient warehouseClient;
        private AppParamServicesClient paramClient;


        /// <summary>
        /// Creates a new <see cref="App"/> instance.
        /// </summary>
        /// 
        public App()
        {
            InitializeComponent();
            System.Net.WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
            Xceed.Silverlight.DataGrid.Licenser.LicenseKey = "DGS10-ARSZ3-MRPR4-KH1A";
            UserSettings = IsolatedStorageSettings.ApplicationSettings;
            file = IsolatedStorageFile.GetUserStoreForApplication();
            warehouseClient = new WarehouseServicesClient();
            paramClient = new AppParamServicesClient();
         
            ThreadPool.QueueUserWorkItem((x) =>
                                             {
                                                 //Deployment.Current.Dispatcher.BeginInvoke(
                                                 //    () => file.IncreaseQuotaTo(1523456786435));
                                                        
                                                 LoadWarehouse();
                                                 GetServerUrl();
                                             
                                                 if (App.Current.HasElevatedPermissions)
                                                 {
                                                     dynamic shell = AutomationFactory.CreateObject("Shell.Application");
                                                     shell.ShellExecute("C:/Report/Report.exe");
                                                 }
                                                
                                               });
            

            if (Current.InstallState == InstallState.Installed)
            {
                Current.CheckAndDownloadUpdateCompleted += OnCheckAndDownloadUpdateCompleted;
                Current.CheckAndDownloadUpdateAsync();
            }

            Current.Exit += new EventHandler(Current_Exit);
            
        }

      

        void warehouseClient_GetAllWarehouseCompleted(object sender, GetAllWarehouseCompletedEventArgs e)
        {
            warehouseClient.GetAllWarehouseCompleted -= new EventHandler<GetAllWarehouseCompletedEventArgs>(warehouseClient_GetAllWarehouseCompleted);
            UserSettings.Add("warehouse",e.Result);
        }

      

        void Current_Exit(object sender, EventArgs e)
        {
            AppClient = new AplicationStateServicesClient();
            AppClient.ClearTransactionCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(AppClient_ClearTransactionCompleted);
            AppClient.ClearTransactionAsync(GlobalVar.CurrentTransaction,GlobalVar.User);
            UserSettings.Clear();
        }

        void AppClient_ClearTransactionCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            AppClient.ClearTransactionCompleted -= new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(AppClient_ClearTransactionCompleted);
        }


        private void OnCheckAndDownloadUpdateCompleted(object sender, CheckAndDownloadUpdateCompletedEventArgs e)
        {
            if (e.UpdateAvailable)
            {
                MessageBox.Show("Aplikasi telah update, Silahkan Restart Aplikasi Anda");
            }
            else if (e.Error != null)
            {
                MessageBox.Show("While checking for an application update, the "
                              + "following message was encountered:"
                              + Environment.NewLine
                              + Environment.NewLine
                              + e.Error.Message);
            }
        }  

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            // This will enable you to bind controls in XAML files to WebContext.Current
            // properties
            //this.Resources.Add("WebContext", WebContext.Current);

            // This will automatically authenticate a user when using windows authentication
            // or when the user chose "Keep me signed in" on a previous login attempt
            //WebContext.Current.Authentication.LoadUser(this.Application_UserLoaded, null);

            // Show some UI to the user while LoadUser is in progress
            this.InitializeRootVisual();
            GlobalVar.OkaSocket = new Socket();
            if (App.Current.IsRunningOutOfBrowser)
                App.Current.MainWindow.WindowState = WindowState.Maximized;
        }

        /// <summary>
        /// Invoked when the <see cref="LoadUserOperation"/> completes. Use this
        /// event handler to switch from the "loading UI" you created in
        /// <see cref="InitializeRootVisual"/> to the "application UI"
        /// </summary>
        private void Application_UserLoaded(LoadUserOperation operation)
        {
        }

        /// <summary>
        /// Initializes the <see cref="Application.RootVisual"/> property. The
        /// initial UI will be displayed before the LoadUser operation has completed
        /// (The LoadUser operation will cause user to be logged automatically if
        /// using windows authentication or if the user had selected the "keep
        /// me signed in" option on a previous login).
        /// </summary>
        protected virtual void InitializeRootVisual()
        {
            //this.busyIndicator = new BusyIndicator();
            //this.busyIndicator.Content = new CoolPage() ; //new MainPage();
            //this.busyIndicator.HorizontalContentAlignment = HorizontalAlignment.Stretch;
            //this.busyIndicator.VerticalContentAlignment = VerticalAlignment.Stretch;

            //this.RootVisual = this.busyIndicator;
           
            this.RootVisual = new MasterPage();
        }

        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            // If the app is running outside of the debugger then report the exception using
            // a ChildWindow control.
      
                e.Handled = true;
                AppClient = new AplicationStateServicesClient();
                AppClient.ClearTransactionCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(AppClient_ClearTransactionCompleted);
                AppClient.ClearTransactionAsync(GlobalVar.CurrentTransaction, GlobalVar.User);
                MessageBox.Show(e.ExceptionObject.Message);
                return;
        }


        public void LoadWarehouse()
        {
            warehouseClient.GetAllWarehouseCompleted += new EventHandler<GetAllWarehouseCompletedEventArgs>(warehouseClient_GetAllWarehouseCompleted);
            warehouseClient.GetAllWarehouseAsync();

        }

        public void GetServerUrl()
        {
            paramClient.GetAppParamListCompleted += new EventHandler<GetAppParamListCompletedEventArgs>(paramClient_GetAppParamListCompleted);
            paramClient.GetAppParamListAsync("ReportUrl");
        }

        void paramClient_GetAppParamListCompleted(object sender, GetAppParamListCompletedEventArgs e)
        {
            paramClient.GetAppParamListCompleted -= new EventHandler<GetAppParamListCompletedEventArgs>(paramClient_GetAppParamListCompleted);
            GlobalVar.ReportUrl = e.Result.FirstOrDefault().AppParamValue;
            UserSettings.Add("url",GlobalVar.ReportUrl);
        }

      }
}